package com.nan.interceptor;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.nan.model.UserInfo;

public class AdminInterceptor implements Interceptor {

	@Override
	public void intercept(Invocation inv) {
			
		Controller controller = inv.getController();
		// 拼装登录完成后需要跳转的地址
		// 即转入登录前页面
		String return_uri = inv.getControllerKey() + "/" + 
							inv.getMethodName();
		String query_string = controller.getRequest().getQueryString();
		// 有 Query String 的话进行拼装
		if (query_string != null)
		{
			return_uri += ("?" + query_string);
		}
		
		UserInfo user = controller.getSessionAttr("mm_login_user");
		if (user != null)
		{
			if (user.getType() != 1)
			{
				controller.renderText("Need admin!");
			}
			else
			{
				inv.invoke();
			}
		}
		else
		{
			try {
				controller.redirect("/user/Login/?return_uri=" + URLEncoder.encode(return_uri, "UTF-8"));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
	}

}
